<template>
  <div class="chat-item" @click="$emit('click')">
    <div class="chat-avatar">
      <img :src="chat.avatar" alt="头像" />
    </div>
    <div class="chat-info">
      <div class="chat-name">{{ chat.userName }}</div>
      <div class="chat-last-message">{{ chat.lastMessage }}</div>
    </div>
    <div class="chat-right">
      <div class="chat-time">{{ formatTime(chat.lastMessageTime) }}</div>
      <div v-if="chat.unreadCount > 0" class="unread-badge">
        {{ chat.unreadCount }}
      </div>
    </div>
  </div>
</template>

<script setup>
defineProps({
  chat: {
    type: Object,
    required: true
  }
})

const formatTime = (timeString) => {
  const date = new Date(timeString)
  const now = new Date()
  
  // 判断是否是同一天
  const isToday = date.toDateString() === now.toDateString()
  
  if (isToday) {
    // 如果是今天，显示时间
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit',
      hour12: false // 使用24小时制
    })
  } else {
    // 如果不是今天，显示日期
    return date.toLocaleDateString('zh-CN', {
      month: '2-digit',
      day: '2-digit'
    })
  }
}
</script>

<style scoped>
.chat-item {
  display: flex;
  align-items: center;
  background: #ffffff;
  border-radius: 0; /* 移除圆角 */
  padding: 1rem;

  position: relative;
  cursor: pointer;

  height: 80px;
  box-sizing: border-box;
  border-bottom: 1px solid #e5e5e5; /* 添加底部边框线 */
}

.chat-item:active {
  background-color: #D9D9D9;
  transition: background-color 0.1s ease;
}

.chat-avatar {
  position: relative;
  margin-right: 1rem;
}

.chat-avatar img {
  width: 53px;
  height: 53px;
  border-radius: 50%;
}

.unread-badge {
  background: red;
  color: white;
  border-radius: 12px;
  min-width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  padding: 0 6px;
}

.chat-info {
  flex: 1;
  margin-right: 1rem;
  width: 0; /* 添加这行以确保flex item可以被压缩 */
}

.chat-name {
  font-family: SourceHanFontBold;
  font-size: 16px;
  color: #000000;
  margin-bottom: 2px; /* 减小与下方文字的间距 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-last-message {
  font-family: SourceHanFont;
  font-size: 12px;
  color: #5b5b5b;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 250px;
}

.chat-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
  min-width: 64px; /* 确保右侧区域有固定最小宽度 */
  flex-shrink: 0; /* 防止右侧区域被压缩 */
}

.chat-time {
  font-size: 0.8rem;
  color: #666;
  margin-bottom: 2px;
}
</style>
